package com.xdu.yunwufog.connection.netty;

import com.xdu.yunwufog.connection.utils.DataBusConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.concurrent.TimeUnit;


public class NettyChannelPoolHandler implements ChannelPoolHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelReleased(Channel ch) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER);
        logger.info("|-->Withdraw channel.Channel ID:"+ch.id());
    }

    @Override
    public void channelAcquired(Channel ch) {
        logger.info("|-->Acquire Channel. Channel ID: " + ch.id());
    }

    @Override
    public void channelCreated(Channel ch) {
        logger.info("|-->Create Channel. Channel ID: " + ch.id() +"Channel REAL HASH: " + System.identityHashCode(ch));
        SocketChannel channel = (SocketChannel) ch;
        channel.config().setKeepAlive(true);
        channel.config().setTcpNoDelay(true);
        channel.pipeline()
                // 开启netty自带的心跳处理器，每10秒发一次心跳
                .addLast(new IdleStateHandler(10,10,10, TimeUnit.MINUTES))
                .addLast(new StringDecoder())
                .addLast(new StringEncoder())
                .addLast(new NettyClientHandler());
    }
}
